//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package admin_roadmap_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/admin_api_serv/admin_common"
	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/roadmap_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/user_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/roadmap_api"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *RoadmapAdminApiImpl) AddWhiteUser(ctx context.Context, req *roadmap_api.AdminAddWhiteUserRequest) (*roadmap_api.AdminAddWhiteUserResponse, error) {
	adminSess, ok := dao.CacheDao.GetAdminSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_api.AdminAddWhiteUserResponse{
			Code:   roadmap_api.AdminAddWhiteUserResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !adminSess.AuthOk {
		return &roadmap_api.AdminAddWhiteUserResponse{
			Code:   roadmap_api.AdminAddWhiteUserResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, adminSess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.RoadmapPerm.AddWhiteUser {
		return &roadmap_api.AdminAddWhiteUserResponse{
			Code:   roadmap_api.AdminAddWhiteUserResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	targetUserItem, err := user_dao.UserInfoDao.GetByName(ctx, req.TargetUserName)
	if err != nil {
		return &roadmap_api.AdminAddWhiteUserResponse{
			Code:   roadmap_api.AdminAddWhiteUserResponse_CODE_NO_TARGET_USER,
			ErrMsg: "目标用户不存在",
		}, nil
	}

	exist, err := roadmap_dao.TagDao.Exist(ctx, req.DefaultTag)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &roadmap_api.AdminAddWhiteUserResponse{
			Code:   roadmap_api.AdminAddWhiteUserResponse_CODE_NO_TAG,
			ErrMsg: "标签不存在",
		}, nil
	}

	nowTime := time.Now().UnixMilli()

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = roadmap_dao.WhiteUserDao.Insert(sessCtx, &roadmap_dao.WhiteUserInfoDbItem{
			UserId:     targetUserItem.UserId,
			DefaultTag: req.DefaultTag,
			UserDesc:   req.UserDesc,
			CreateTime: nowTime,
			UpdateTime: nowTime,
		})
		if err != nil {
			return nil, err
		}
		return &roadmap_api.AdminAddWhiteUserResponse{
			Code: roadmap_api.AdminAddWhiteUserResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_api.AdminAddWhiteUserResponse), nil
}
func (apiImpl *RoadmapAdminApiImpl) UpdateWhiteUser(ctx context.Context, req *roadmap_api.AdminUpdateWhiteUserRequest) (*roadmap_api.AdminUpdateWhiteUserResponse, error) {
	adminSess, ok := dao.CacheDao.GetAdminSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_api.AdminUpdateWhiteUserResponse{
			Code:   roadmap_api.AdminUpdateWhiteUserResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !adminSess.AuthOk {
		return &roadmap_api.AdminUpdateWhiteUserResponse{
			Code:   roadmap_api.AdminUpdateWhiteUserResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, adminSess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.RoadmapPerm.UpdateWhiteUser {
		return &roadmap_api.AdminUpdateWhiteUserResponse{
			Code:   roadmap_api.AdminUpdateWhiteUserResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	targetUserItem, err := user_dao.UserInfoDao.GetByName(ctx, req.TargetUserName)
	if err != nil {
		return &roadmap_api.AdminUpdateWhiteUserResponse{
			Code:   roadmap_api.AdminUpdateWhiteUserResponse_CODE_NO_TARGET_USER,
			ErrMsg: "目标用户不存在",
		}, nil
	}

	exist, err := roadmap_dao.WhiteUserDao.Exist(ctx, targetUserItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &roadmap_api.AdminUpdateWhiteUserResponse{
			Code:   roadmap_api.AdminUpdateWhiteUserResponse_CODE_NO_TARGET_USER,
			ErrMsg: "目标用户记录不存在",
		}, nil
	}

	exist, err = roadmap_dao.TagDao.Exist(ctx, req.DefaultTag)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &roadmap_api.AdminUpdateWhiteUserResponse{
			Code:   roadmap_api.AdminUpdateWhiteUserResponse_CODE_NO_TAG,
			ErrMsg: "标签不存在",
		}, nil
	}

	nowTime := time.Now().UnixMilli()

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = roadmap_dao.WhiteUserDao.Update(sessCtx, targetUserItem.UserId, req.DefaultTag, req.UserDesc, nowTime)
		if err != nil {
			return nil, err
		}
		return &roadmap_api.AdminUpdateWhiteUserResponse{
			Code: roadmap_api.AdminUpdateWhiteUserResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_api.AdminUpdateWhiteUserResponse), nil
}

func (apiImpl *RoadmapAdminApiImpl) RemoveWhiteUser(ctx context.Context, req *roadmap_api.AdminRemoveWhiteUserRequest) (*roadmap_api.AdminRemoveWhiteUserResponse, error) {
	adminSess, ok := dao.CacheDao.GetAdminSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_api.AdminRemoveWhiteUserResponse{
			Code:   roadmap_api.AdminRemoveWhiteUserResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !adminSess.AuthOk {
		return &roadmap_api.AdminRemoveWhiteUserResponse{
			Code:   roadmap_api.AdminRemoveWhiteUserResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, adminSess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.RoadmapPerm.RemoveWhiteUser {
		return &roadmap_api.AdminRemoveWhiteUserResponse{
			Code:   roadmap_api.AdminRemoveWhiteUserResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := roadmap_dao.WhiteUserDao.Exist(ctx, req.TargetUserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &roadmap_api.AdminRemoveWhiteUserResponse{
			Code: roadmap_api.AdminRemoveWhiteUserResponse_CODE_OK,
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = roadmap_dao.WhiteUserDao.Remove(sessCtx, req.TargetUserId)
		if err != nil {
			return nil, err
		}
		return &roadmap_api.AdminRemoveWhiteUserResponse{
			Code: roadmap_api.AdminRemoveWhiteUserResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_api.AdminRemoveWhiteUserResponse), nil
}

func (apiImpl *RoadmapAdminApiImpl) ListWhiteUser(ctx context.Context, req *roadmap_api.AdminListWhiteUserRequest) (*roadmap_api.AdminListWhiteUserResponse, error) {
	emptyList := []*roadmap_api.WhiteUserInfo{}

	adminSess, ok := dao.CacheDao.GetAdminSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_api.AdminListWhiteUserResponse{
			Code:          roadmap_api.AdminListWhiteUserResponse_CODE_WRONG_SESSION,
			ErrMsg:        "会话不存在",
			WhiteUserList: emptyList,
		}, nil
	}
	if !adminSess.AuthOk {
		return &roadmap_api.AdminListWhiteUserResponse{
			Code:          roadmap_api.AdminListWhiteUserResponse_CODE_NOT_AUTH,
			ErrMsg:        "未授权会话",
			WhiteUserList: emptyList,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, adminSess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.RoadmapPerm.Read {
		return &roadmap_api.AdminListWhiteUserResponse{
			Code:          roadmap_api.AdminListWhiteUserResponse_CODE_NO_PERMISSION,
			ErrMsg:        "没有权限",
			WhiteUserList: emptyList,
		}, nil
	}

	count, err := roadmap_dao.WhiteUserDao.Count(ctx)
	if err != nil {
		return nil, err
	}

	whiteUserItemList, err := roadmap_dao.WhiteUserDao.List(ctx, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	//获取用户信息
	userIdList := []string{}
	for _, whiteUserItem := range whiteUserItemList {
		userIdList = append(userIdList, whiteUserItem.UserId)
	}
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, userIdList)
	if err != nil {
		return nil, err
	}
	userItemMap := map[string]*user_dao.UserInfoDbItem{}
	for _, userItem := range userItemList {
		userItemMap[userItem.UserId] = userItem
	}
	//生成结果
	whiteUserList := []*roadmap_api.WhiteUserInfo{}
	for _, whiteUserItem := range whiteUserItemList {
		whiteUser := whiteUserItem.ToWhiteUserInfo()
		userItem, ok := userItemMap[whiteUserItem.UserId]
		if ok {
			whiteUser.UserName = userItem.UserName
			whiteUser.UserDisplayName = userItem.BasicInfo.DisplayName
			whiteUser.UserLogoUri = userItem.BasicInfo.LogoUri
		}
		whiteUserList = append(whiteUserList, whiteUser)
	}
	return &roadmap_api.AdminListWhiteUserResponse{
		Code:          roadmap_api.AdminListWhiteUserResponse_CODE_OK,
		TotalCount:    count,
		WhiteUserList: whiteUserList,
	}, nil
}
